using Elmah;

namespace Triad.Common
{
    using System;
    using System.Text;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    /// <summary>
    /// Functions for allowing Remote Javascript to be created from the server to run on the client.
    /// </summary>
    public class RemoteJScript
    {
        
        private static readonly StringBuilder m_strError = new StringBuilder();

        private static void ClearError()
        {
            m_strError.Length = 0;
        }


        /// <summary>
        /// Writes to the Elmah Log and pops up a window.
        /// </summary>
        /// <param name="p_Exception">The exception.</param>
        /// <param name="placeHolder">The Container control to hold the literal.</param>
        /// <param name="p_strScript">The script.</param>
        /// <remarks>
        /// Author: tim.fischer,   4/23/2008 - 11:11 AM
        /// Modified By: 
        /// </remarks>
        public static void WriteLog(Exception p_Exception, WebControl placeHolder, string p_strScript)
        {
            m_strError.AppendLine(JScriptEncode(p_Exception.Message,false));
            p_strScript = JScriptEncode(p_strScript, false);
            p_strScript += "ShowError('" + m_strError + "',1);";
            RunJScript(p_strScript, placeHolder);
            ErrorLog.GetDefault(HttpContext.Current);
            ClearError();
        }


        /// <summary>
        /// Sets the focus vai javascript to a control.
        /// </summary>
        /// <param name="p_ctlFocus">The element to get focus.</param>
        /// <param name="ctlWarpMain">The CTL warp main.</param>
        /// <remarks>
        /// Author: tim.fischer,   4/23/2008 - 11:11 AM
        /// Modified By: 
        /// </remarks>
        public static void SetFocus(WebControl p_ctlFocus, WebControl ctlWarpMain)
        {
            string strScript = string.Format("<script type='text/javascript'>APP.Common.setFocus('{0}');</script>", p_ctlFocus.ClientID);
            ctlWarpMain.Controls.Add(new LiteralControl(strScript));
        }

        /// <summary>
        /// Sets the focus via javascript to a control.
        /// </summary>
        /// <param name="p_ControlClientId">The control client id.</param>
        /// <param name="p_WarpMain">The CTL warp main.</param>
        /// <remarks>
        /// Author: ann.melewski,   5/15/2008 - 3:03 PM
        /// Modified By: 
        /// </remarks>
        public static void SetFocus(string p_ControlClientId, WebControl p_WarpMain)
        {
            string strScript = string.Format("<script type='text/javascript'>APP.Common.setFocus('{0}');</script>", p_ControlClientId);
            p_WarpMain.Controls.Add(new LiteralControl(strScript));
        }


        /// <summary>
        /// Writes the log.
        /// </summary>
        /// <param name="strException">The exception.</param>
        /// <param name="ctlContainer">The warp main.</param>
        /// <remarks>
        /// Author: tim.fischer,   4/23/2008 - 11:12 AM
        /// Modified By: 
        /// </remarks>
        public static void WriteLog(Exception strException, WebControl ctlContainer)
        {
            m_strError.AppendLine(Convert.ToString((strException.Message)));
            string strScript = string.Format("TF.APP.Common.cShowError('{0}',1);", JScriptEncode(m_strError.ToString(), false));
            RunJScript(strScript, ctlContainer);
            ErrorLog.GetDefault(HttpContext.Current);
            ClearError();
        }

        /// <summary>
        /// Create a new literal control within the specified warp panel and insert javascript
        /// </summary>
        /// <param name="strScript">The script.</param>
        /// <param name="ctlContainer">The warp main.</param>

        public static void RunJScript(string strScript, WebControl ctlContainer)
        {
            string m_strScript = string.Format("<script type='text/javascript'>{0}</script>", strScript);
            ctlContainer.Controls.Add(new LiteralControl(m_strScript));
        }


        /// <summary>
        /// Used to cause the client to redirect a page.  Needed due to Infragistics WARP functionality
        /// </summary>
        /// <param name="strPageName">The page name.</param>
        /// <returns></returns>
        public static string PageRedirect(string strPageName)
        {
            return string.Format("window.location='{0}';", strPageName);
        }

        /// <summary>
        /// Causes the client to redirect to another page - necessary as a WARP control will not allow server transfers
        /// </summary>
        /// <param name="p_strPageName">The page name.</param>
        /// <param name="ctlContainer">The warp Control.</param>
        /// <remarks>
        /// Author: tim.fischer,   4/23/2008 - 9:47 AM
        /// Modified By:
        /// </remarks>
        public void PageRedirect(string p_strPageName, WebControl ctlContainer)
        {
            RunJScript(string.Format("window.location='{0}';", p_strPageName), ctlContainer);
        }
        /// <summary>
        /// Show an error msg via javascript
        /// </summary>
        /// <param name="Error_Type">Type of the error_.</param>
        /// <param name="p_Message">The message.</param>
        /// <returns></returns>

        public static string ShowError(Err_Type Error_Type, string p_Message)
        {
            return string.Format("TF.APP.Common.cShowError('{0}',{1});", JScriptEncode(p_Message, false), (int)Error_Type);
        }
        /// <summary>
        /// wrapper function for RunJScript to show an error
        /// </summary>
        /// <param name="Error_Type">Type of the error_.</param>
        /// <param name="p_Message">The message.</param>
        /// <param name="ctlContainer">The CTL warp main.</param>

        public static void ShowError(Err_Type Error_Type, string p_Message, WebControl ctlContainer)
        {
            string strScript = string.Format("TF.APP.Common.cShowError('{0}',{1});", JScriptEncode(p_Message, false), (int)Error_Type);
            RunJScript(strScript, ctlContainer);
        }

        /// <summary>
        /// Wrapper function for RunJScript to show an error.  
        /// Allows for a function to be called after the message box has been closed.
        /// </summary>
        /// <param name="Error_Type">Type of the error_.</param>
        /// <param name="p_Message">The message.</param>
        /// <param name="ctlContainer">The CTL warp main.</param>
        /// <param name="p_CallBackFunction">The call back function.</param>
        /// <remarks>
        /// Author: ann.melewski,   5/15/2008 - 5:01 PM
        /// Modified By: 
        /// </remarks>
        public static void ShowError(Err_Type Error_Type, string p_Message, WebControl ctlContainer, string p_CallBackFunction)
        {
            string strScript = string.Format("TF.APP.Common.cShowError('{0}',{1},'{2}');", JScriptEncode(p_Message, false), (int)Error_Type, JScriptEncode(p_CallBackFunction, false));
            RunJScript(strScript, ctlContainer);
        }


        /// <summary>
        /// Show Error
        /// </summary>
        /// <param name="Error_Type">Type of the error_.</param>
        /// <param name="p_Exception">The exception.</param>
        /// <returns></returns>

        public static string ShowError(Err_Type Error_Type, Exception p_Exception)
        {
            string strScript = string.Format("TF.APP.Common.cShowError('{0}',{1});", JScriptEncode(p_Exception.Message, false), (int)Error_Type);
            return strScript;
        }
        /// <summary>
        /// Encode text to be passed as a URL or within javascript
        /// </summary>
        /// <param name="p_value">The .</param>
        /// <param name="p_forUrl">The URL.</param>
        /// <returns></returns>
        public static string JScriptEncode(string p_value, Boolean p_forUrl)
        {
            string builder;
            if (String.IsNullOrEmpty(p_value)) return p_value;
                try
                {

                    builder = p_value.Replace("%", "%%");
                    builder = builder.Replace("\\", "\\\\");
                    builder = builder.Replace("'", "\\'");
                    builder = builder.Replace(Convert.ToString((char)9), "\\t");
                    builder = builder.Replace(Convert.ToString((char)10), "\\n");
                    builder = builder.Replace(Convert.ToString((char)13), "\\r");
                    builder = builder.Replace(Convert.ToString((char)34), "\\" + Convert.ToString((char)34));
                    //\' - single quote, needed for character literals 
                    //\" - double quote, needed for string literals 
                    //\\ - backslash 
                    //\0 - Unicode character 0 
                    //\a - Alert (character 7) 
                    //\b - Backspace (character 8) 
                    //\f - Form feed (character 12) 
                    //\n - New line (character 10) 
                    //\r - Carriage return (character 13) 
                    //\t - Horizontal tab (character 9) 
                    //\v - Vertical quote (character 11) 
                    if (p_forUrl)
                        builder = builder.Replace(" ", "%20");
                }
                catch
                {
                    return p_value;
                }
            return builder;

        }
    }
}